package com.zhulin.android.edoctor.fragment;

import java.util.ArrayList;
import java.util.List;

import com.zhulin.android.edoctor.net.BaseRequest;
import com.zhulin.android.edoctor.net.RequestResultCallback;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.widget.Toast;

public class BaseFragment extends Fragment{
	
	public List<BaseRequest> listRequest=new ArrayList<BaseRequest>();

	protected Handler mHandler=new Handler(new android.os.Handler.Callback() {
		
		@Override
		public boolean handleMessage(Message msg) {
			dissProgressDialog();
			if(msg.what==1){
				onSuccess(msg.obj);
			}else if(msg.what==-1){
				onFail((Exception) msg.obj);
			}
			return false;
		}
	});
	
	ProgressDialog mProgressDialog;
	public void ShowProgressDialog(String title,String message){
		mProgressDialog=ProgressDialog.show(getActivity(), title, message,true,true);
		mProgressDialog.show();
		
		mProgressDialog.setOnCancelListener(new OnCancelListener() {
			
			@Override
			public void onCancel(DialogInterface dialog) {
				closeRequest();
			}
		});
	}
	
	public void dissProgressDialog()
	{
		if(mProgressDialog!=null && mProgressDialog.isShowing()){
			mProgressDialog.dismiss();
		}
	}
	
	public RequestResultCallback requestResultCallback=new RequestResultCallback() {
		
		@Override
		public void onSuccess(Object obj) {
			mHandler.sendMessage(mHandler.obtainMessage(1, obj));
		}
		
		@Override
		public void onFail(Exception e) {
			mHandler.sendMessage(mHandler.obtainMessage(-1, e));
		}
	};
	
	public void onSuccess(Object o) {
		
	}

	public void onFail(Exception e) {
		if(e!=null){
			Toast(getActivity(), ""+e.getMessage(), Toast.LENGTH_LONG);
		}
	}
	
	public void Toast(Context mContext,String text,int l){
		Toast.makeText(mContext, text, l).show();
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		closeRequest();
	}
	
	private void closeRequest(){
		for (int i = 0; i < listRequest.size(); i++) {
			BaseRequest baseRequest=listRequest.get(i);
			if(baseRequest!=null){
				if(baseRequest.getRequest()!=null){
					baseRequest.getRequest().abort();
				}
			}
		}
		
		
	}
}
